// 静态文件服务器

const path = require( 'path' );

let http = require('http'), 
fs = require('fs'),
base = './data';

http.createServer( (req, res) =>{
  pathname = path.normalize(  base + req.url )
  console.log(pathname)

  fs.stat(pathname, (err, stats) => {
    if(err){
      console.log(err)
      res.writeHead(404)
      res.write('Resource missing 404\n')
      res.end()
      
    }else{
      res.setHeader('Content-Type','text/html')
      // create and pipe readable stream
      let file = fs.createReadStream(pathname);

      file.on('open', () => {
        res.statusCode = 200
        file.pipe(res)
      })

      file.on('error' , (err) => {
        console.log(err)
        res.writeHead(403)
        res.write('file missing or permission problem')
        res.end()
      })
    }
  })

}).listen(3000)

console.log('Server running....')



